package com.noble.meether.fragment.mail.store;

import com.noble.dbcenter.DBRequest;
import com.noble.dbcenter.entity.CollectionCallBack;
import com.noble.meether.chat.MessageConstant;
import com.noble.meether.db.DBMgr;
import com.noble.meether.db.callbace.DBCallback;
import com.noble.meether.fragment.mail.bean.UserMessage;
import com.squareup.sqlbrite.BriteDatabase;

import java.util.List;

/**
 * 聊天消息列表
 */
public class DBMessageListCache {
    private BriteDatabase mDatabase;
    private DBMgr.DBHandler handler;

    public DBMessageListCache(BriteDatabase database, DBMgr.DBHandler handler) {
        this.mDatabase = database;
        this.handler = handler;
    }

    private void makeDBCallback(DBCallback callback, long ret) {
        if (callback != null) {
            callback.OnDBExecuted(ret >= 0 ? MessageConstant.OK : MessageConstant.ERROR);
        }
    }

    // ================================================= 插入 =============================================

    /**
     * 插入单条
     */
    public void insertMsg(final UserMessage data, final DBCallback callback) {
        handler.post(() -> {
            long result = insertLetter(data);
            makeDBCallback(callback, result);
        });
    }

    /**
     * 多条消息插入
     */
    public void insertMsgBatch(final List<UserMessage> list, final DBCallback callback) {
        handler.post(() -> {
            long ret = MessageConstant.OK;
            BriteDatabase.Transaction transaction = mDatabase.newTransaction();
            try {
                for (UserMessage item : list) {
                    ret = insertLetter(item);
                    if (ret != MessageConstant.OK) {
                        break;
                    }
                }
                transaction.markSuccessful();
            } finally {
                transaction.end();
            }
            makeDBCallback(callback, ret);
        });
    }

    private long insertLetter(final UserMessage data) {
        if (data == null) {
            return MessageConstant.ERROR;
        }

        try {
            long ret = mDatabase.insert(MsgListTable.TABLE_NAME, MsgListTable.toContentValues(data));
            return ret >= 0 ? MessageConstant.OK : MessageConstant.ERROR;
        } catch (Exception e) {
            e.printStackTrace();
            return MessageConstant.ERROR;
        }
    }

    // ================================================= 更新 =============================================
    public long updateLetter(UserMessage data) {
        if (data == null) {
            return MessageConstant.ERROR;
        }

        try {
            long ret = mDatabase.update(MsgListTable.TABLE_NAME, MsgListTable.toContentValues(data), MsgListTable.COLUMN_ID + " = ? ", String.valueOf(data.getWhisperID()));
            return ret >= 0 ? MessageConstant.OK : MessageConstant.ERROR;
        } catch (Exception e) {
            e.printStackTrace();
            return MessageConstant.ERROR;
        }
    }

    // ================================================= 查询 =============================================

    /**
     * 查询消息记录
     */
    @SuppressWarnings("unchecked")
    public void queryMsgList(DBMessageListCallback queryCallback) {
        new DBRequest.Builder()
                .tableName(MsgListTable.TABLE_NAME)
                .querySql("SELECT * FROM " + MsgListTable.TABLE_NAME + ";")
                .mapper(MsgListTable.MAPPER)
                .getList(getSubscriber(queryCallback));
    }

    /**
     * @return 数据库查询回调
     */
    private CollectionCallBack<UserMessage> getSubscriber(final DBMessageListCallback queryCallback) {
        return new CollectionCallBack<UserMessage>() {
            @Override
            public void onFailure(int code, String message) {
                if (queryCallback != null)
                    queryCallback.onFailure(code, message);
            }

            @Override
            public void onCompleted() {
            }

            // 获取查询数据列表
            @Override
            public void onSuccess(List<UserMessage> data) {
                if (queryCallback != null)
                    queryCallback.onSuccess(data);
            }
        };
    }

    public interface DBMessageListCallback {

        void onFailure(int code, String message);

        void onSuccess(List<UserMessage> data);
    }


}
